package beanstao.util.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import org.dom4j.Element;

import beanstao.util.setting.Setting;

public class MultiThreadPoolSetting extends Setting<Element>
{
	/**
	 * @return 池中所保存的线程数，包括空闲线程。
	 */
	public int getCorePoolSize()
	{
		return corePoolSize;
	}

	/**
	 * @return 池中允许的最大线程数(采用LinkedBlockingQueue时没有作用)
	 */
	public int getMaximumPoolSize()
	{
		return maximumPoolSize;
	}

	/**
	 * @return 当线程数大于核心时，此为终止前多余的空闲线程等待新任务的最长时间，线程池维护线程所允许的空闲时间。
	 */
	public int getKeepAliveTime()
	{
		return keepAliveTime;
	}

	/**
	 * @return 执行前用于保持任务的队列（缓冲队列）。此队列仅保持由 execute 方法提交的 Runnable 任务。
	 */
	public BlockingQueue<Runnable> getWorkQueue()
	{
		return workQueue;
	}

	public TimeUnit getTimeUnit()
	{
		return timeUnit;
	}

	public RejectedExecutionHandler getExecutionHandler()
	{
		return executionHandler;
	}

	private int corePoolSize;
	private int maximumPoolSize;
	private int keepAliveTime;
	private final TimeUnit timeUnit = TimeUnit.SECONDS;
	private BlockingQueue<Runnable> workQueue;
	private final RejectedExecutionHandler executionHandler = new ThreadPoolExecutor.CallerRunsPolicy();

	@Override
	protected void fillSettingData(Element element)
	{
		corePoolSize = Integer.valueOf(element.selectSingleNode("corePoolSize").getText().trim());
		maximumPoolSize = Integer.valueOf(element.selectSingleNode("maximumPoolSize").getText().trim());
		keepAliveTime = Integer.valueOf(element.selectSingleNode("keepAliveTime").getText().trim());
		workQueue = new ArrayBlockingQueue<Runnable>(Integer.valueOf(element.selectSingleNode("ArrayBlockingQueue").getText().trim()));
	}

	/**
	 * 本类型的单建实例
	 * 
	 * @return 返回本类型的单建实例(延迟加载,并对多线程进行处理)
	 */
	public static MultiThreadPoolSetting ME()
	{
		return Single.instance;
	}

	/**
	 * 为单建模式设计的内部静态类型
	 */
	static class Single
	{
		/**
		 * 多线程锁
		 */
		static ReentrantLock lock = new ReentrantLock();
		static
		{
			synchronized (lock)
			{
				instance = new MultiThreadPoolSetting();
			}
		}
		static MultiThreadPoolSetting instance;
	}

	/**
	 * 针对单建模式,私有化本类型构造函数
	 */
	private MultiThreadPoolSetting()
	{
	}

}
